package cn.com.yto56.cainiao.exponent.elasticsearch.plugin;

import cn.com.yto56.basic.framework.core.util.DateUtil;
import cn.com.yto56.basic.framework.core.util.EmptyUtils;
import cn.com.yto56.basic.framework.model.rest.MutiRequest;
import cn.com.yto56.basic.framework.plugin.chain.config.ExecutorRequest;
import cn.com.yto56.basic.framework.plugin.elasticsearch.TagRequest;
import cn.com.yto56.cainiao.exponent.dto.ExpUploadRequest;
import cn.com.yto56.cainiao.exponent.dto.ExponentRequest;
import cn.com.yto56.cainiao.exponent.plugin.ExponentConvertPlugin;
import java.util.ArrayList;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@Order(1)
public class TimelyCanvassConvertPlugIn extends ExponentConvertPlugin<ExpUploadRequest, MutiRequest<ExponentRequest>> {


  /**
   * 扩展类型
   */
  @Override
  protected String extentionName() {
    return "及时揽收率";
  }


  /**
   * 根据参数判断是否可以执行该插件
   */
  @Override
  protected Boolean allowExecute(ExecutorRequest<ExpUploadRequest, MutiRequest<ExponentRequest>> parameter) {
    return EmptyUtils.isNotEmpty(parameter)
        &&
        EmptyUtils.isNotEmpty(parameter.getInitParameter())
        &&
        parameter.getInitParameter().getFileName().startsWith(extentionName())
        &&
        EmptyUtils.isNotEmpty(parameter.getInitParameter().getRowValues()
        );
  }


  @Override
  protected MutiRequest<ExponentRequest> convert(ExecutorRequest<ExpUploadRequest, MutiRequest<ExponentRequest>> parameter) {
    parameter.getInitParameter().getRowValues().stream().forEach(n -> {
      ExponentRequest exponentRequest = new ExponentRequest();
      exponentRequest.setExtProperties(new ArrayList<>());
      exponentRequest.setConsumerTime(new Date());
      exponentRequest.setExponentType(extentionName());
      exponentRequest.setPullDate(DateUtil.toDate(parameter.getInitParameter().getDateFmt()));
      exponentRequest.setWayBillNo(n.get("运单号").replace(" ", ""));
      exponentRequest.setDeliveryTime(DateUtil.toDate(n.get("卖家发货时间"), "yyyy-MM-dd HH:mm:ss"));
      exponentRequest.getExtProperties().add(new TagRequest().setTagCode(parameter.getInitParameter().getArea()));
      parameter.getOutputParameter().getItems().add(exponentRequest);
    });
    return parameter.getOutputParameter();
  }
}
